package com.lingying.caiwudailikehudaun.utils;

import org.apache.commons.codec.digest.DigestUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class GetFileMD5 {
    /**
     * 读取文件MD5值
     * @param path
     * @return
     */
    public static String getFileMD5(String path){
        InputStream inputStream = null;
        String md5=null;
        try {
            //url路径
            URL url=new URL(path);
            //获取连接
            HttpURLConnection connection=(HttpURLConnection)url.openConnection();
            connection.setConnectTimeout(3*1000);
            //设置请求头
            connection.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.110 Safari/537.36");

            inputStream = connection.getInputStream();
            //DigestUtils为org.apache.commons.codec.digest.DigestUtils下的类
            md5 = DigestUtils.md5Hex(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally{
            try {
                if (inputStream != null) {
                    //关闭流
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return md5;
    }
    }
